import helpers.mengy_CRC

CRC_OBJ = helpers.mengy_CRC.CRC_PACK()


def ask_03(addr=1, start=0, length=80):
    funCode = 3
    pack = "{:02X}{:02X}{:04X}{:04x}".format(addr, funCode, start, length)
    return CRC_OBJ.gen_st_crc(pack)


def write_05_06(addr=1, funCode=5, start=0, value=0xFF00):
    pack = "{:02X}{:02X}{:04X}{:04x}".format(addr, funCode, start, value)
    return CRC_OBJ.gen_st_crc(pack)


def write_10(addr=1, start=0, data=(1,)):
    dataNum = len(data)
    bytesNum = 2 * dataNum
    dataStr = "".join(("{:04X}".format(i) for i in data))
    pack = "{:02X}10{:04X}{:04x}{:02X}{}".format(addr, start, dataNum, bytesNum, dataStr)
    return CRC_OBJ.gen_st_crc(pack)


def calRecvLength(bytesPack):
    if len(bytesPack) == 0:
        return 0
    if bytesPack[1] == 0x03 and len(bytesPack) == 8:
        return 2 * (bytesPack[4] * 256 + bytesPack[5]) + 5
    elif bytesPack[1] in (0x05, 0x06) and len(bytesPack) == 8:
        return 8
    elif bytesPack[1] == 0x10:
        return 8
    else:
        return 5


def getErrCodeMean(data_send: bytes, data_recv: bytes):
    """get error code meaning"""
    funCode = data_send[1]
    if data_recv[1] - funCode == 0x80:
        errCode = data_recv[2]
        if errCode == 0x02:
            return "无效地址"
        elif errCode == 0x03:
            return "无效数据"
        elif errCode == 0x04:
            return "从设备出错"
        elif errCode == 0x06:
            return "从设备忙"
        else:
            return "报文内容异常"
    return ""
